package cn.tx.coolshark.controller;

import cn.tx.coolshark.mapper.BannerMapper;
import cn.tx.coolshark.mapper.CategoryMapper;
import cn.tx.coolshark.pojo.entity.Banner;
import cn.tx.coolshark.pojo.entity.Category;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.util.List;

@RestController
/*在类上添加@RequestMapping，
可以将该类中所有处理请求的方法的映射路径中相同部分抽取出来*/
@RequestMapping("/banner/")
public class BannerController {

    @Autowired
    private BannerMapper bannerMapper;

    //@Value注解的作用是给下面的变量赋值
    //${XXX}会自动到application.properties中找imagesPath的配置信息
    @Value("${imagesPath}")
    private String dirPath;

    @RequestMapping("select")
    public List<Banner> select(){
        return bannerMapper.select();
    }

    @RequestMapping("delete")
    public void delete(int id){
        //得到原来图片的路径
        String url = bannerMapper.selectUrlById(id);
        //原来图片删除了
        new File(dirPath+url).delete();
        bannerMapper.deleteById(id);
    }

    @RequestMapping("insert")
    public void insert(String url){
        bannerMapper.insert(url);
    }

    @RequestMapping("selectById")
    public Banner selectById(int id){
        return bannerMapper.selectById(id);
    }
    @RequestMapping("update")
    public void update(@RequestBody Banner banner){
        //得到原来图片的路径
        String url = bannerMapper.selectUrlById(banner.getId());
        //对比新图片和原来图片的路径
        if(url.equals(banner.getUrl())){
            return;
        }
        //原来图片删除了
        new File(dirPath+url).delete();
        //执行修改操作
        bannerMapper.update(banner);
    }
}
